package com.propertypoint.presentation.actions;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.propertypoint.presentation.model.Agent;
import com.propertypoint.service.business.RegistrationServiceImpl;
import com.propertypoint.service.general.RegistrationService;
import com.propertypoint.util.MultipartRequestHandler;
import com.propertypoint.util.PropertyPointConstants;

/**
 * Servlet implementation class FileUploadServlet
 */
@WebServlet("/FileUploadServlet")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private RegistrationService registrationService = new RegistrationServiceImpl();
	 
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileUploadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/* *
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 * response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	// this will store uploaded files

	/***************************************************
	 * URL: /upload doPost(): upload the files and other parameters
	 ****************************************************/
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,IOException {

		HttpSession session = request.getSession();
		String imagePath = getServletContext()
				.getInitParameter("imageLocation");
		String fileName;
		try {
			fileName = MultipartRequestHandler.uploadByApacheFileUpload(
					request, imagePath);
			request.setAttribute("upload_status", true);

			if (fileName != null && session.getAttribute("user") != null) {

				Agent agent = (Agent) session.getAttribute("user");
				agent.setPicture(fileName);
				
				try {
					registrationService.updateProfilePicture(agent);
					agent.setPictureUrl("img/profilepics/"+fileName);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		} catch (IOException e1) {
			request.setAttribute("upload_status", false);
		}
		session.setAttribute("tab_status", "profilePicture");

		RequestDispatcher rd = getServletContext().getRequestDispatcher(
				PropertyPointConstants.HOME_PAGE);
		rd.forward(request, response);

	}

}
